<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\EntrustPermissionRoleRepository;
use HiCommon\Repository\EntrustPermissionsRepository;
use HiCommon\Repository\ShopUserRepository;

class PermissionsService extends BaseService
{
    /**
     * 拖拽移动权限
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_drag_move_node($arr_input){
        $s_action = $arr_input['action'];
        $n_drag_node_id = intval($arr_input['drag_node_id']);
        $n_target_node_id = intval($arr_input['target_node_id']);
        switch ($s_action)
        {
            case 'prev'://拖拽节点移动到目标节点之前
                $res = self::drag_move_node_drop_prev($n_drag_node_id,$n_target_node_id);
                break;
            case 'inner'://拖拽节点移动到目标节点里面
                $res = self::drag_move_node_drop_inner($n_drag_node_id,$n_target_node_id);
                break;
            case 'next'://拖拽节点移动到目标节点之后
                $res = self::drag_move_node_drop_next($n_drag_node_id,$n_target_node_id);
                break;
            default:
                $res = hello_error('操作类型错误');
        }
        return $res;
    }

    /**
     * 拖拽节点移动到目标节点之前
     *
     * @param int $n_drag_node_id
     * @param int $n_target_node_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function drag_move_node_drop_prev($n_drag_node_id = 0,$n_target_node_id = 0){
        // 1-拖拽节点是目标节点同级
        //查询目标节点
        $arr_target_node = EntrustPermissionsRepository::base_find_one($n_target_node_id);
        $arr_node = [
          'id'=>$n_drag_node_id,
          'pid'=>$arr_target_node['pid'],
        ];

        // 2-拖拽节点的排序在目标节点之前
        //查询目标节点父级下的子级
        $arr_where = ['pid'=>$arr_target_node['pid']];
        $arr_child_node = EntrustPermissionsRepository::normal_all_where_sort($arr_where)->toArray();
        $arr_child_node = collect($arr_child_node)->whereNotIn('id',[$n_drag_node_id])->values()->all();
        $arr_data = [];
        $n_sort = 0;
        foreach ($arr_child_node as $value)
        {
            $arr_data[] = [
              'id'=>$value['id'],
              'pid'=>$value['pid'],
              'sort'=>$n_sort,
            ];
            if($value['id'] == $n_target_node_id){
                $sort = $n_sort - 1;
            }
            $n_sort = $n_sort + 2;
        }
        $arr_data[] = [
          'id'=>$arr_node['id'],
          'pid'=>$arr_node['pid'],
          'sort'=>$sort,
        ];
        $res = EntrustPermissionsRepository::base_update_batch($arr_data);
        if ($res == 0){
            return hello_error('操作失败');
        }

        return  hello_success('操作成功');

    }

    /**
     * 拖拽节点移动到目标节点里面
     *
     * @param int $n_drag_node_id
     * @param int $n_target_node_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function drag_move_node_drop_inner($n_drag_node_id = 0,$n_target_node_id = 0){
        // 1-拖拽节点是目标节点子级
        $arr_node = [
          'id'=>$n_drag_node_id,
          'pid'=>$n_target_node_id,
        ];

        // 2-拖拽节点的排序是目标节点子级集合的最后一个
        //查询目标节点下的子级
        $arr_where = ['pid'=>$n_target_node_id];
        $arr_child_node = EntrustPermissionsRepository::normal_all_where_sort($arr_where)->toArray();
        $arr_data = [];
        $n_sort = 0;
        foreach ($arr_child_node as $value)
        {
            $arr_data[] = [
              'id'=>$value['id'],
              'pid'=>$value['pid'],
              'sort'=>$n_sort,
            ];
            $n_sort++;

        }
        $arr_data[] = [
          'id'=>$arr_node['id'],
          'pid'=>$arr_node['pid'],
          'sort'=>$n_sort,
        ];
        $res = EntrustPermissionsRepository::base_update_batch($arr_data);
        if ($res == 0){
            return hello_error('操作失败');
        }
        return  hello_success('操作成功');
    }

    /**
     * 拖拽节点移动到目标节点之后
     *
     * @param int $n_drag_node_id
     * @param int $n_target_node_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function drag_move_node_drop_next($n_drag_node_id = 0,$n_target_node_id = 0){
        // 1-拖拽节点是目标节点同级
        //查询目标节点
        $arr_target_node = EntrustPermissionsRepository::base_find_one($n_target_node_id);
        $arr_node = [
          'id'=>$n_drag_node_id,
          'pid'=>$arr_target_node['pid'],
        ];


        // 2-拖拽节点的排序在目标节点之后
        //查询目标节点父级下的子级
        $arr_where = ['pid'=>$arr_target_node['pid']];
        $arr_child_node = EntrustPermissionsRepository::normal_all_where_sort($arr_where)->toArray();
        $arr_child_node = collect($arr_child_node)->whereNotIn('id',[$n_drag_node_id])->values()->all();
        $arr_data = [];
        $n_sort = 0;
        foreach ($arr_child_node as $value)
        {
            $arr_data[] = [
              'id'=>$value['id'],
              'pid'=>$value['pid'],
              'sort'=>$n_sort,
            ];
            if($value['id'] == $n_target_node_id){
                $sort = $n_sort + 1;
            }
            $n_sort = $n_sort + 2;
        }
        $arr_data[] = [
          'id'=>$arr_node['id'],
          'pid'=>$arr_node['pid'],
          'sort'=>$sort,
        ];
        $res = EntrustPermissionsRepository::base_update_batch($arr_data);
        if ($res == 0){
            return hello_error('操作失败1');
        }
        return  hello_success('操作成功');

    }

    /**
     * 添加一条权限
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_add_one($arr_input){
        filter_input_data($arr_input);
        //添加
        $res = EntrustPermissionsRepository::base_add_one($arr_input)->toarray();
        if(empty($res)){
            return hello_error('添加失败');
        }
        return  hello_success('添加成功',$res);
    }

    /**
     * 修改一条权限
     *
     * @param array $arr_input
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_edit_one(array $arr_input)
    {
        filter_input_data($arr_input);

        $arr_input['id'] = (int)$arr_input['id'];
        if ($arr_input['id'] <= 0) {
            return hello_error('数据id不能为空');
        }

        $res = EntrustPermissionsRepository::base_edit_one($arr_input);
        if ($res === false) {
            return hello_error('操作失败');
        }
        return hello_success('成功',$arr_input);
    }

    /**
     * 删除权限
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_delete_one($n_id)
    {
        if ($n_id <= 0) {
            return hello_error('数据id不能为空');
        }

        //            //有子数据的不能删除
        //            $res = EntrustPermissionsRepository::get_all_by_where(['pid'=>$n_id])->toarray();
        //            if(!empty($res)){
        //                return hello_error('有子数据,不能删除');
        //            }

        $arr_whereIn = tree_childrenids(cache_permission(),$n_id);
        $res = EntrustPermissionsRepository::base_delete_by_wherein('id',$arr_whereIn,true);
        if($res === false){
            return hello_error('操作失败');
        }
        return  hello_success('成功');
    }

    /**
     * 商户后台用户验证权限
     *
     * @param string $route
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_shop_authority_auth(string $route)
    {
        $n_admin_id = admin_user_id();

        //主页和首页不需要验证权限
        if ($route == 'admin_index' || $route == 'admin_index_main' || $route == 'admin_login_out') {
            return  hello_success('主页和首页不需要验证权限');
        }

        //超级用户admin不需要验证权限 其他用户需验证权限
        if (is_admin_super() === true) {
            return  hello_success('超级用户admin不需要验证权限');
        }
        else {

            /*//查询权限表中是否添加路由权限
            $oc_res = collect(get_permission_cache());
            if (is_null($oc_res->where('alias', $route)
                                         ->first())) {
                return hello_error('权限表中未添加路由权限');
            }*/

            //检查登录用户是否有该权限
            $oc_res = collect(cache_user_permissions_for_admin($n_admin_id));
            if (is_null($oc_res->where('alias', $route)
                               ->first())) {
                return hello_error('您没有访问权限！请联系超级管理员');
            }

        }
    }

    /**
     * 根据商户管理员id查询对应商户所有权限
     * 商户所有权限 = 商户后台 + 商户app权限
     *
     * @param int $n_uid
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_shop_for_whole_permissions($n_uid = 0){
        $arr_shop_user = ShopUserRepository::find_one_login($n_uid)->toarray();
        $n_shop_cate = $arr_shop_user['shop_base']['cate'];
//        predis_str_set('aa',cache_permission_for_shop_check());
        if($n_shop_cate == 1){
            $arr_data = [
              'shop'=>cache_permission_for_shop_check(),
              'shop_app'=>cache_permission_for_shop_check_app(),
            ];
        }
        elseif($n_shop_cate == 2){
            //        $s_model = 'shop_repair';
            $arr_data = [
              'shop'=>cache_permission_for_shop_repair(),
              'shop_app'=>cache_permission_for_shop_repair_app(),
            ];
        }
        else{
            $arr_data = [
              'shop'=>[],
              'shop_app'=>[],
            ];
        }
        return $arr_data;
    }

    /**
     * 根据商户管理员id查询对应商户所有权限(包含已选中权限)
     * 商户所有权限 = 商户后台 + 商户app权限
     *
     * @param int $n_uid
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_shop_for_whole_permissions_with_selected($n_uid = 0,$n_id = 0){

        //查询商户的所有权限
        $res = self::api_shop_for_whole_permissions($n_uid);
        $arr_shop = $res['shop'];
        $arr_shop_app = $res['shop_app'];
//        list($arr_shop,$arr_shop_app) = self::api_shop_for_whole_permissions($n_uid);

        //查询角色权限
        $arr_where = ['role_id'=>$n_id];
        $res = EntrustPermissionRoleRepository::base_get_all_by_where($arr_where)->toarray();
        $arr_role_permission = array_to_arr_ids($res,'permission_id');

        //处理商户后台选中情况
        foreach ($arr_shop as $key=>$value)
        {
            if(in_array($value['id'],$arr_role_permission)){
                $arr_shop[$key]['is_checked'] = true;
            }
        }

        //处理商户APP选中情况
        foreach ($arr_shop_app as $key=>$value)
        {
            if(in_array($value['id'],$arr_role_permission)){
                $arr_shop_app[$key]['is_checked'] = true;
            }
        }

        $arr_data = [
          'shop'=>$arr_shop,
          'shop_app'=>$arr_shop_app,
        ];

        return $arr_data;
    }


}